<template>
  <div class="dashboard-container">
    <div class="app-container">
      <set-role ref="setRoleRef" :show-set-role-dialog.sync="showSetRoleDialog" :user-id="userId" @closeDialog="showSetRoleDialog=false"></set-role>
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条数据</span>
        <div slot="after">
          <el-button type="primary" size="small" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="small" @click="exportExcel">导出</el-button>
          <el-button type="success" size="small" @click="addFormVisible = true">新增员工</el-button>
        </div>
      </page-tools>
      <el-card>
        <el-table
          fit
          :data="tableData"
          border
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column align="center" type="index" label="序号" width="60px"> </el-table-column>
          <el-table-column align="center" prop="username" label="姓名" sortable width="100px"> </el-table-column>
          <el-table-column align="center" prop="staffPhoto" label="头像" sortable width="100px">
            <template slot-scope="{ row }">
              <img class="listPhoto" :src="row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="mobile" label="手机号" sortable width="130px">
          </el-table-column>
          <el-table-column align="center" prop="workNumber" label="工号" sortable width="120px"> </el-table-column>
          <el-table-column align="center" prop="formOfEmployment" label="聘用形式" sortable :formatter="formFormatter" width="100px">
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" sortable width="100px"> </el-table-column>
          <el-table-column align="center" prop="timeOfEntry" label="入职时间" sortable width="120px">
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column align="center" prop="enableState" label="账户状态" sortable>
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right" width="300px">
            <template slot-scope="{ row }">
              <el-button type="text" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="role(row.id)">角色</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-pagination layout="prev, pager, next" :page-size="page.size" :current-page="page.page" :total="total" @current-change="changePage">
      </el-pagination>
    </div>
    <!-- sync是子组件去改变父组件数据的一个语法糖 -->
    <add-employee :add-form-visible.sync="addFormVisible" @closeDialog="addFormVisible=false"></add-employee>
  </div>
</template>
<script>
import { getList, delEmployee } from '@/api/employee'
import employeeEnum from '@/api/constant/employees'
import addEmployee from './components/add.vue'
import { formatDate } from '@/utils/filters';
import setRole from './components/setRole.vue'
export default {
  components: {
    addEmployee,
    setRole
  },
  data() {
    return {
      showSetRoleDialog: false,
      addFormVisible: false,
      total: 0,
      page: {
        page: 1,
        size: 10
      },
      tableData: [],
      userId: null
    };
  },
  created() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const res = await getList(this.page)
      this.total = res.total;
      this.tableData = res.rows
      console.log(this.tableData);
    },
    formFormatter(row, column, cellValue) {
      const obj = employeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    stateFormatter(row, column, cellValue) {
      console.log(cellValue);
      const obj = employeeEnum.workingState.find(item => Number(item.id) === cellValue)
      console.log(obj);
      return obj ? obj.value : '未知'
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getTableData()
    },
    async del(id) {
      console.log(id);
      try {
        await this.$confirm('确定删除该员工吗？')
        await delEmployee(id)
        this.getTableData()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error);
      }
    },
    async exportExcel() {
      function jsonFormatter(headers, rows) {
        // 1.按表头顺序 2.转化为[['tom', '13832198312'], ['jerry', '13232313213']]
        const result = rows.map(item => {
          return Object.keys(headers).map(cell => {
            if (headers[cell] === 'timeOfEntry' || headers[cell] === 'correctionTime') {
              return formatDate(item[headers[cell]])
            } else if (headers[cell] === 'formOfEmployment') {
              const obj = employeeEnum.hireType.find(obj => {
                return obj.id === item[headers[cell]]
              })
              return obj ? obj.value : '未知'
            }
            return item[headers[cell]]
          })
        });
        // console.log(result);
        return result;
      }
      const { rows } = await getList({ page: 1, size: this.total })
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: jsonFormatter(headers, rows),
          filename: '员工基本信息',
          bookType: 'xlsx'
        })
      })
    },
    async role(id) {
      this.userId = id
      console.log(this.$refs.setRoleRef);
      await this.$refs.setRoleRef.getUserDetail(id)
      this.showSetRoleDialog = true
    }
  }

};
</script>

<style>
.el-pagination{
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.el-card {
  padding: 10px 0;
  margin-bottom: 10px
}
.el-card__body {
  padding: 0 20px
}
.listPhoto {
  width: 80px;
}
</style>
